package product

import (
	"context"
	"github.com/pkg/errors"
	"github.com/xinliangnote/go-gin-api/configs"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func NewModel() *Product {
	return new(Product)
}

func (p *Product) Create(db *mongo.Client) (id string, err error) {
	cfg := configs.Get().Mongodb
	client := db.Database(cfg.Config.Name).Collection("product")
	one, err := client.InsertOne(context.TODO(), p)
	if err != nil {
		return "", err
	}
	return one.InsertedID.(primitive.ObjectID).String(), nil
}

func (p *Product) List(db *mongo.Client, pageIndex uint, pageSize uint) (list []Product, err error) {
	var productList []Product

	cfg := configs.Get().Mongodb
	client := db.Database(cfg.Config.Name).Collection("product")
	skip := int64((pageIndex - 1) * pageSize)
	findOptions := options.Find()
	findOptions.SetSort(bson.D{{"_id", -1}})
	findOptions.SetSkip(skip)
	findOptions.SetLimit(int64(pageSize))

	find, err := client.Find(context.TODO(), bson.D{{"deleteStatus", "0"}}, findOptions)
	if err != nil && !errors.Is(err, mongo.ErrNoDocuments) {
		return nil, err
	}

	err = find.All(context.TODO(), &productList)
	if err != nil {
		return nil, err
	}

	return productList, nil
}

func (p *Product) Update(db *mongo.Client) error {
	cfg := configs.Get().Mongodb
	client := db.Database(cfg.Config.Name).Collection("product")
	objId, _ := primitive.ObjectIDFromHex(p.Id)
	filter := bson.D{{"_id", objId}}
	update := bson.M{"$set": bson.M{
		"productName":  p.ProductName,
		"fee":          p.Fee,
		"months":       p.Months,
		"type":         p.Type,
		"categoryId":   p.CategoryId,
		"categoryName": p.CategoryName,
	}}

	product := new(Product)
	_ = client.FindOne(context.TODO(), filter).Decode(&product)

	_, err := client.UpdateOne(context.TODO(), filter, update)
	return err
}

func (p *Product) Delete(db *mongo.Client) error {
	cfg := configs.Get().Mongodb
	client := db.Database(cfg.Config.Name).Collection("product")
	objId, _ := primitive.ObjectIDFromHex(p.Id)
	filter := bson.D{{"_id", objId}}
	update := bson.M{"$set": bson.M{
		"deleteStatus": p.DeleteStatus,
	}}
	_, err := client.UpdateOne(context.TODO(), filter, update)
	return err
}

func (p *Product) Count(db *mongo.Client) (count int64, err error) {
	cfg := configs.Get().Mongodb
	client := db.Database(cfg.Config.Name).Collection("product")
	count, err = client.CountDocuments(context.TODO(), bson.D{{"deleteStatus", "0"}})
	if err != nil && !errors.Is(err, mongo.ErrNoDocuments) {
		return 0, err
	}
	return count, nil
}
